﻿CREATE PROCEDURE [dbo].[GoodsVsContragentsInsert]
(
	@GoodsId int,
	@ContragentId int,
	@GoodsCode int,
	@GoodsName varchar(150),
	@CountryName varchar(20),
	@ManufacturerName varchar(70),
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50)
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @intNextId int
	SET NOCOUNT ON

IF (@GoodsId Is Null) OR (@ContragentId Is Null) OR (@GoodsCode Is Null) OR (@GoodsName Is Null)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF (ltrim(@GoodsName) = '')
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 2, @strMsg = 'Незаполнено наименование товара у контрагента!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF EXISTS (SELECT TOP 1 ID FROM [CA].[GoodsVsContragents] 
WHERE ContragentId = @ContragentId AND GoodsCode = @GoodsCode 
AND GoodsName = @GoodsName 
AND ( (CountryName = @CountryName) OR (@CountryName Is Null AND CountryName Is Null) )
AND ( (@ManufacturerName = ManufacturerName) OR (@ManufacturerName Is Null AND ManufacturerName Is Null) )
AND ToDelete = 0 )
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 3, @strMsg = 'Дублируется товар у контрагента!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF NOT EXISTS (SELECT DepartmentId FROM PR.DepartmentOptions WHERE DepartmentId = 0 ) 
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 4, @strMsg = 'Изменять данные справочников можно только в офисе!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF NOT EXISTS (SELECT * FROM CA.Goods WHERE ID = @GoodsId AND ToDelete = 0)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 5, 
	@strMsg = 'Отсутствует товар с идентификатором ' + cast(@GoodsId as varchar(20)) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
--получение значения идентификатора
EXEC @intRet = dbo.GetNextCounterFor 'Common', @intNextId OUTPUT
IF @intRet <> 0 RETURN @intRet

	SET NOCOUNT OFF;
INSERT INTO [CA].[GoodsVsContragents] ( Id, [GoodsId], [ContragentId], [GoodsCode], [GoodsName], [CountryName], [ManufacturerName], 
[Note], [MD], [MW], ToDelete) 
VALUES (@intNextId, @GoodsId, @ContragentId, @GoodsCode, @GoodsName, @CountryName, @ManufacturerName, 
@Note, @MD, @MW, 0);
	
/*SELECT Id, GId, GoodsId, ContragentId, GoodsCode, GoodsName, CountryName, ManufacturerName, 
Note, MD, MW, ToDelete
FROM CA.GoodsVsContragents WHERE (Id = @intNextId)*/

RETURN 0